import { watch, ref } from 'vue'
import { isString } from '@/utils/is'
import { useCache } from '@/hooks/web/useCache'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import { useI18n } from '@/hooks/web/useI18n'
const { wsCache } = useCache()
const localeStore = useLocaleStoreWithOut()
const curLang = localeStore.getCurrentLocale.lang
const appStore = useAppStoreWithOut()

export const useTitle = (newTitle?: string) => {
  const { t } = useI18n()
  let str = ''
  if (curLang == 'en') {
    str = 'Easy Low-Code Platform'
  } else if (wsCache.get('userInfo') != null) {
    str = wsCache.get('userInfo').data.user.fullName
  } else {
    str = 'Easy Low-Code Platform'
  }
  str = str + '-' + t(newTitle as string)
  const title = ref(newTitle ? str : appStore.getTitle)
  // console.log(newTitle)
  // newTitle ? `${appStore.getTitle} - ${t(newTitle as string)}` : appStore.getTitle
  watch(
    title,
    (n, o) => {
      if (isString(n) && n !== o && document) {
        document.title = n
      }
    },
    { immediate: true }
  )

  return title
}
